package com.netease.financial.module.asset;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.netease.financial.base.push.PushConstants;
import com.netease.financial.base.push.PushUtils;
import com.netease.financial.common.constant.Constants;
import com.netease.financial.common.intent.FortuneClubIntent;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.common.util.WebUtils;
import com.netease.financial.common.util.preferences.BadgePreferencesHelper;
import com.netease.financial.base.web.WebStoragePreferencesHelper;
import com.netease.financial.internal.di.components.MainComponent;
import com.netease.financial.module.web.WebViewTabFragment;

import org.json.JSONObject;

import javax.inject.Inject;

import cn.bingoogolapple.badgeview.BGABadgeable;

public class AssetFragment extends WebViewTabFragment implements AssetView {

    private static final String TAG = AssetFragment.class.getSimpleName();

    @Inject
    AssetPresenter assetPresenter;

    private Receiver mReceiver;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        registerReceiver();
        View view = super.onCreateView(inflater, container, savedInstanceState);
        handleIntent(getActivity().getIntent());
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initialize();
        loadAsset();
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        boolean loginWithAnotherAccount = intent.getBooleanExtra("login_with_another_account", false);

        NfsLog.d(TAG, "loginWithAnotherAccount:" + loginWithAnotherAccount);
        if (loginWithAnotherAccount) {
            WebStoragePreferencesHelper.setUserNeedLogout(true);
            WebUtils.removeLocalStorageItem(getWebView(), WebStoragePreferencesHelper.KEY_LOCAL_STORAGE_ACCESS_TOKEN);
            WebUtils.removeLocalStorageItem(getWebView(), WebStoragePreferencesHelper.KEY_LOCAL_STORAGE_USER_ID);
            getWebViewHelper().handleLocalStorageItems();
            BadgePreferencesHelper.setUnreadPrivateMessageCount(0);
            refreshTabBadgeView();
            WebStoragePreferencesHelper.setUserNeedLogout(false);
            getWebView().reload();
        }
    }

    private void initialize() {
        getComponent(MainComponent.class).inject(this);
        assetPresenter.setView(this);
    }

    /**
     * Loads asset.
     */
    private void loadAsset() {
        assetPresenter.initialize();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unregisterReceiver();
    }

    @Override
    public String getInitialPageUrl() {
        return Constants.getAssetUrl();
    }

    @Override
    public boolean isTabBadgeShouldShow() {
        return BadgePreferencesHelper.isAssetTabBadgeShouldShow();
    }

    @Override
    public void showBadge(BGABadgeable badgeView) {
        int unreadMessageCount = BadgePreferencesHelper.getUnreadPrivateMessageCount();
        if (unreadMessageCount > 0) {
            badgeView.showTextBadge(String.valueOf(unreadMessageCount));
        } else {
            badgeView.showCirclePointBadge();
        }
    }

    @Override
    public void showTabBadgeIfNeed() {
        refreshTabBadgeView();
    }

    private void handleIncomingSiteMessageEvent(Bundle bundle) {
        JSONObject jsonObject = PushUtils.getExtraJSONObject(bundle);
        int badgeNumber = PushUtils.getBadgeNumber(jsonObject);
//        assetPresenter.checkUnreadSiteMessageCount();
        NfsLog.d(TAG, "handleIncomingSiteMessageEvent.badgeNumber:" + badgeNumber);

        assetPresenter.changeTabBadgeNumber(badgeNumber);
    }

    private void registerReceiver() {
        if (mReceiver == null) {
            mReceiver = new Receiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(PushConstants.getPushAction(PushConstants.PUSH_TYPE_SITE_MESSAGE));
            filter.addAction(FortuneClubIntent.ACTION_LOGIN_WITH_ANOTHER_ACCOUNT);
            getActivity().registerReceiver(mReceiver, filter);
        }
    }

    private void unregisterReceiver() {
        if (mReceiver != null) {
            getActivity().unregisterReceiver(mReceiver);
            mReceiver = null;
        }

    }

    private final class Receiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                NfsLog.d(TAG, intent.getAction());
                if (PushConstants.getPushAction(PushConstants.PUSH_TYPE_SITE_MESSAGE).equals(intent.getAction())) {
                    handleIncomingSiteMessageEvent(intent.getExtras());
                }
            }

        }
    }

}
